import datetime
import glob
import os
import uuid
from PIL import Image, ImageDraw, ImageFont
import traineeskill

def get_formatted_time():
    now = datetime.datetime.now()
    year = str(now.year).zfill(2)
    month = str(now.month).zfill(2)
    day = str(now.day).zfill(2)
    hour = str(now.hour).zfill(2)
    minute = str(now.minute).zfill(2)
    second = str(now.second).zfill(2)
    time_string = f"{year}{month}{day}-{hour}{minute}{second}"
    return time_string

class Trainee:
    def __init__(self):
        self.imginfos = None
        self.name = ""
        self.infos = {}
        self.genius = []
        self.skills = []
        self.skillscores = []
        self.lock = False
        self.score = 0
        t = get_formatted_time()
        uuid_str = uuid.uuid4().hex
        self.dir = f'{t}-{uuid_str[:8]}'
    def Clear(self):
        self.imginfos = None
        self.name = ""
        self.infos = {}
        self.genius = []
        self.skills = []
        self.skillscores = []
        self.score = 0
    def SetLock(self, lock:bool):
        self.lock = lock
    def SetImgInfos(self, imginfos:Image):
        self.imginfos = imginfos
    def SetName(self, name:list[str]):
        self.name = ''
        for n in name:
            self.name += n
    def SetInfos(self, infos:list[str]):
        for info in infos:
            info = info.replace('：', ':')
            ss = info.split(':')
            if len(ss) == 2:
                key = ss[0].replace('，','')
                key = key.replace('、','')
                self.infos[key] = ss[1]
    def SetGenius(self, genius:list[str]):
        self.genius = genius
    def AddSkill(self, skill:str):
        self.skills.append(skill)
        self.skillscores.append(0)
    def SetSkillScore(self, index:int,score:int):
        self.skillscores[index] = score
    def SetScore(self, score:int):
        self.score = score
    def GetId(self):
        a = "null"
        b = "null"
        try:
            a = self.infos['初始']
            b = self.infos['成长']
        except:
            pass
        s = f'{a}_{b}'
        if b == "null":
            debug = 1
        return s
    def CheckExist(self,quality:str):
        dir  = f'./capture/{quality}'
        id = self.GetId()
        s = f'{dir}/{id}_*.png'
        files = glob.glob(s)
        bexist = False
        for file in files:
            if os.path.exists(file):
                bexist = True
                # subfile = file[len(id)+1:]
                # subfilelock:bool = (subfile.find(f'[L]') == 0)
                # if subfilelock != self.lock:
                #     if subfilelock:
                #         catfile = subfile[3:]
                #     else:
                #         catfile = subfile
                #     lockflag = ''
                #     if self.lock:
                #         lockflag = '[L]'
                #     new_file = f'{dir}/{id}_{lockflag}{catfile}'
                #     print(f'更名文件: {file} -> {new_file}')
                #     os.renames(file,new_file)
                break
        return bexist
    def GenCsv(self,quality:str):
        try:
            dir  = f'./capture/{quality}'
            if not os.path.exists(dir):
                os.makedirs(dir)
            with open(f'{dir}/test.csv', "a", encoding="gb2312") as f:
                f.write(f"{self.name},")
                for v in self.infos.values():
                    f.write(f"{v},")
                genius = ''
                for geniu in self.genius:
                    genius += geniu
                f.write(f"{genius},")
                f.write(f"{self.score}\n")
                for i in range(len(self.skills)):
                    skill = self.skills[i].replace(',','')
                    f.write(f"{skill},")
                f.write(f"\n")
                for i in range(len(self.skills)):
                    f.write(f"{self.skillscores[i]:.2f},")
                f.write(f"\n")
        except Exception as e:
            print("生成CSV文件失败,e=",e)
    def GenImg(self,index:int,quality:str):
        dir  = f'./capture/{quality}'
        if not os.path.exists(dir):
            os.makedirs(dir)
        id = self.GetId()
        lockflag = ''
        if self.lock:
            lockflag = '[L]'
        imgfilename = f'./{dir}/{id}_{lockflag}[{self.score:.2f}]_{self.name}.png'
        image = Image.new('RGB', ( 1024, 760), color=(255, 255, 255))
        image.paste(self.imginfos, (0, 0))
        draw = ImageDraw.Draw(image)
        font = ImageFont.truetype("simhei.ttf", 20)
        for i in range(len(self.skills)):
            text = self.skills[i]
            skillitem = traineeskill.ts.GetItem(text)
            key = skillitem[0]
            value = skillitem[1]
            s = f"{i+1}|{key}|{value[0]}|{text[:15]}|{self.skillscores[i]:.2f}"
            color= (0, 0, 0)
            if key == 'None':
                color = (255, 0, 0)
            elif value[2] == 1:
                color = (0, 255, 0)
            draw.text((528+10, 57+22*i),s, font=font, fill=color)
        s = f"总分：{self.score:.2f}"
        draw.text((528+10, 57+22*20),s, font=font, fill=(0, 0, 0))
        # image.show()
        uuid_str = uuid.uuid4().hex
        image.save(imgfilename)

    
